const Controller = require('egg').Controller
const fs = require('fs')
// node.js 路径操作对象
const path = require('path')
// egg.js Controller
const awaitWriteStream = require('await-stream-ready').write
// 管道读入一个虫洞。
const sendToWormhole = require('stream-wormhole')

class TaskController extends Controller {
  /* 后台 */
  async uploadTask() {
    const { ctx, config } = this
    const stream = await ctx.getFileStream();
    // 文件名:随机数+时间戳+原文件后缀
    // path.extname(stream.filename).toLocaleLowerCase()为后缀名（.jpg,.png等）
    const filename = Math.random().toString(36).substr(2) + new Date().getTime() + path.extname(stream.filename).toLocaleLowerCase();
    // 图片存放在静态资源public/img文件夹下
    const target = path.join(config.baseDir, 'app/public/task', filename);
    // 生成一个文件写入 文件流
    const writeStream = fs.createWriteStream(target);
    try {
      // 异步写入文件流
      await awaitWriteStream(stream.pipe(writeStream));
    } catch (err) {
      // 如果出现错误，关闭管道
      await sendToWormhole(stream);
      throw err;
    }

    ctx.body = {
      code: '0',
      filename: path.join('/public/task', filename),
      desc: '上传成功'
    };
  }
  //添加打卡
  async createTask() {
    try {
      const { ctx } = this
      const { finish_write, finish_video, sign_id, task_images } = ctx.request.body
      await ctx.model.Task.create({
        finish_write, 
        finish_video, 
        sign_id, 
        task_images
      })
      ctx.body = {
        code: '0',
        desc: '打卡创建成功'
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '打卡创建失败'
      }
    }
  }
  //编辑打卡
  async editTask() {
    try {
      const { ctx } = this
      const { id, finish_write, finish_video, sign_id, task_images } = ctx.request.body
      await ctx.model.Task.update({
        finish_write, 
        finish_video, 
        sign_id, 
        task_images
      }, {
        where: {
          id
        }
      })
      return ctx.body = {
        code: '0',
        desc: '打卡信息修改成功'
      }
    } catch(error) {
      return ctx.body = {
        code: '-1',
        desc: '打卡信息修改失败'
      }
    }
  }
  //删除打卡
  async deleteTask() {
    try {
      const { ctx } = this
      const { id } = ctx.request.body
      await ctx.model.Task.destroy({
        where: {
          id
        }
      })
      ctx.body = {
        code: '0',
        desc: '打卡删除成功'
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '打卡删除失败',
        err: error
      }
    }
  }
  //批量删除打卡
  async batchDeleteTasks() {
    try {
      const { ctx, app } = this
      const { Op } = app.Sequelize
      const { ids } = ctx.request.body
      await ctx.model.Task.destroy({
        where: {
          id: {
            [Op.in]: ids
          }
        }
      })
      ctx.body = {
        code: '0',
        desc: '打卡批量删除成功'
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '打卡批量删除失败',
        err: error
      }
    }
  }
}

module.exports = TaskController